﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Text;

namespace Coldairarrow.Util.Helper
{
   public class SMSVerification
    {
        #region 短信发送
        public static bool SendSms(string Telphone, string Code, out string MessageResult)
        {
            //OSS的访问ID
            string accessKeyId = "LTAI5tBM6x6xxSzEaK1mqGf8";
            //OSS的访问密钥
            string accessKeySecret = "EDaw6gqvINs15crz4FiHtqVSsyGPfD";
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action = "SendSms";
            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为20个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.AddQueryParameters("PhoneNumbers", Telphone);
                //必填:短信签名-可在短信控制台中找到
                request.AddQueryParameters("SignName", "乐邑有约");
                //必填:短信模板-可在短信控制台中找到
                request.AddQueryParameters("TemplateCode", "SMS_223045199");
                //可选:模板中的变量替换JSON串,如模板内容为"您的验证码为${code}"时,此处的值为
                string TemplateParam = "{\"code\":\"" + Code + "\"}";
                request.AddQueryParameters("TemplateParam", TemplateParam);
                try
                {
                    CommonResponse response = client.GetCommonResponse(request);
                    Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
                    var result = JsonConvert.DeserializeObject<AliResDTO>(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));  // 其中，T是Json字符串匹配的对象类型
                    if (result.Message == "OK" && result.Message == "OK")
                    {
                        MessageResult = null;
                        return true;
                    }
                    else
                    {
                        MessageResult = result.Message;
                        return false;
                    }
                }
                catch (ServerException e)
                {
                    throw new BusException(e.ToString(), errorCode: -1);
                }

            }
            catch (ServerException e)
            {
                throw new BusException(e.ToString(), errorCode: -1);
            }

            MessageResult = null;
            return true;
        }

        private class AliResDTO { 
            public string RequestId { set; get; }

            public string Message { set; get; }

            public string Code { set; get; }
        }
        #endregion
    }
}
